<template>
  <div class="temperature-chart">
    <div class="header-title">
      <dv-decoration-3 style="width:100px;height:20px;" />
      <div class="monitor-title">温度检测数据统计</div>
      <dv-decoration-3 style="width:100px;height:20px;" />
    </div>
    <div class="chart-container">
      <div class="chart-header">
        <div class="time-selector">
          <span class="active">周</span>
          <span>月</span>
        </div>
        <div class="legend">
          <div class="legend-item">
            <span class="dot air"></span>
            <span>空气温度</span>
          </div>
          <div class="legend-item">
            <span class="dot soil"></span>
            <span>土壤温度</span>
          </div>
        </div>
      </div>
      <div ref="tempChartRef" style="width: 100%; height: 200px; margin-bottom: 2px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { get } from '@/utils/request'
import router from '@/router'

let tempChart = null
const tempChartRef = ref(null)

const handleResize = () => {
  tempChart?.resize()
}

const initTempChart = () => {
  if (tempChartRef.value) {
    tempChart?.dispose()
    tempChart = echarts.init(tempChartRef.value)
    const option = {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(0,0,0,0.7)',
        borderColor: '#03d3ec',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [],
        axisLine: {
          lineStyle: {
            color: '#03d3ec'
          }
        },
        axisLabel: {
          color: '#03d3ec'
        }
      },
      yAxis: {
        type: 'value',
        name: '单位/°C',
        nameTextStyle: {
          color: '#03d3ec',
          padding: [0, 30, 0, 0]
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(3,211,236,0.1)',
            type: 'dashed'
          }
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#03d3ec'
          }
        },
        axisLabel: {
          color: '#03d3ec'
        }
      },
      series: [
        {
          name: '空气温度',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          data: [],
          lineStyle: {
            color: '#03d3ec',
            width: 2
          },
          itemStyle: {
            color: '#03d3ec'
          }
        },
        {
          name: '土壤温度',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          data: [],
          lineStyle: {
            color: '#ff4d4f',
            width: 2
          },
          itemStyle: {
            color: '#ff4d4f'
          }
        }
      ]
    }
    tempChart.setOption(option)
  }
}

const fetchTemperatureData = async () => {
  try {
    // 确保有token
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('No token available, skipping request')
      return
    }

    const airResponse = await get('/at/latest')
    const soilResponse = await get('/st/latest')

    // 添加调试日志
    console.log('Air temperature response:', airResponse)
    console.log('Soil temperature response:', soilResponse)

    // 检查响应数据的结构
    if (!airResponse || !airResponse.values || !airResponse.dayOfWeeks) {
      console.error('Invalid air temperature data structure:', airResponse)
      return
    }

    if (!soilResponse || !soilResponse.values || !soilResponse.dayOfWeeks) {
      console.error('Invalid soil temperature data structure:', soilResponse)
      return
    }

    // 直接使用响应中的数据
    const airTemperature = airResponse.values
    const soilTemperature = soilResponse.values
    const dayOfWeeks = airResponse.dayOfWeeks

    if (tempChart) {
      const updatedOption = {
        xAxis: {
          data: dayOfWeeks
        },
        series: [
          {
            name: '空气温度',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            data: airTemperature,
            lineStyle: {
              color: '#03d3ec',
              width: 2
            },
            itemStyle: {
              color: '#03d3ec'
            }
          },
          {
            name: '土壤温度',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            data: soilTemperature,
            lineStyle: {
              color: '#ff4d4f',
              width: 2
            },
            itemStyle: {
              color: '#ff4d4f'
            }
          }
        ]
      }
      tempChart.setOption(updatedOption)
    }
  } catch (error) {
    if (error.response?.status === 401) {
      // 处理401错误
      router.push('/login')
    } else {
      console.error('Failed to fetch temperature data:', error)
    }
  }
}

onMounted(() => {
  initTempChart()
  // 延迟执行第一次数据获取
  setTimeout(fetchTemperatureData, 500)
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  tempChart?.dispose()
  tempChart = null
})
</script>

<style lang="scss" scoped>
.temperature-chart {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header-title {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;

    .monitor-title {
      font-size: 14px;
      color: #03d3ec;
      white-space: nowrap;
      margin: 0 10px;
    }
  }

  .chart-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0 10px 10px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;

      .time-selector {
        span {
          padding: 2px 10px;
          color: #03d3ec;
          cursor: pointer;
          margin-right: 10px;

          &.active {
            background: rgba(3, 211, 236, 0.2);
            border-radius: 4px;
          }
        }
      }

      .legend {
        display: flex;
        gap: 20px;

        .legend-item {
          display: flex;
          align-items: center;
          color: #ffffff;
          font-size: 12px;

          .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;

            &.air {
              background-color: #03d3ec;
            }

            &.soil {
              background-color: #ff4d4f;
            }
          }
        }
      }
    }
  }
}
</style>
